#!/bin/bash

sudo dpkg --add-architecture armhf
sudo apt update
sudo apt upgrade -y
sudo apt install -y cmake gcc-arm-linux-gnueabihf libc6:armhf
sudo apt reinstall -y libc6-dev

mkdir $HOME/.local/share/tiny/cross

rm -rf $HOME/.local/share/tiny/tmp
mkdir $HOME/.local/share/tiny/tmp
cd $HOME/.local/share/tiny/tmp

box86_url="https://github.com/ptitSeb/box86"
box64_url="https://github.com/ptitSeb/box64"

mirror_sites=(
    "https://github.moeyy.xyz/"
    "https://mirror.ghproxy.com/"
    ""
)

for mirror in "${mirror_sites[@]}"; do
    url="${mirror}${box86_url}"
    echo "尝试从 $url 下载box86..."
    git clone "${url}"
    if [ $? -eq 0 ]; then
        echo "成功下载box86"
        break
    fi
    if [ -z "$mirror" ]; then
        rm -rf $HOME/.local/share/tiny/tmp
        echo '仓库克隆失败...退出安装...'
        exit
    fi
done

for mirror in "${mirror_sites[@]}"; do
    url="${mirror}${box64_url}"
    echo "尝试从 $url 下载box64..."
    git clone "${url}"
    if [ $? -eq 0 ]; then
        echo "成功下载box64"
        break
    fi
    if [ -z "$mirror" ]; then
        rm -rf $HOME/.local/share/tiny/tmp
        echo '仓库克隆失败...退出安装...'
        exit
    fi
done

echo "正在编译box86..."
cd box86
mkdir build
cd build
cmake .. -DARM64=1 -DBAD_SIGNAL=ON -DCMAKE_BUILD_TYPE=RelWithDebInfo
make -j
cd ../..
mv box86/build/box86 ../cross
mv box86/x86lib ../cross

echo "正在编译box64..."
cd box64
mkdir build
cd build
cmake .. -DARM64=1 -DBAD_SIGNAL=ON -DCMAKE_BUILD_TYPE=RelWithDebInfo
make -j
cd ../..
mv box64/build/box64 ../cross
mv box64/x64lib ../cross

cd ..
rm -rf tmp

echo '安装完成'
